import axios from 'axios'; // 引入axios
import QS from 'qs'; // 引入qs模块，用来序列化post类型的数据


//默认参数设置
axios.defaults.timeout = 10000;
axios.defaults.baseURL = 'http://127.0.0.1';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

//get请求
function get(url, params) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    }).then(res => {
      resolve(res.data);
    }).catch(err => {
      reject(err.data)
    })
  });
}

//post请求
function post(url, params) {
  return new Promise((resolve, reject) => {
    axios.post(url, QS.stringify(params)).then(res => {
      resolve(res.data);
    }).catch(err => {
      reject(err.data);
    })

  });
}

function put(url) {
  return new Promise((resolve, reject) => {
    axios.put(url).then(res => {
      resolve(res.data);
    }).catch(err => {
      reject(err.data)
    })
  });
}

function deletes(url) {
  return new Promise((resolve, reject) => {
    axios.put(url).then(res => {
      resolve(res.data);
    }).catch(err => {
      reject(err.data)
    })
  });
}

function request(url, method, params) {
  switch (method) {
    case 'get':
      return get(url, params);
      break;
    case 'post':
      return post(url, params);
      break;
    case 'put':
      return put(url);
      break;
    case 'delete':
      return deletes(url);
      break;
  }
}

export default request
